/**
 * teachingJournalData.js
 * 获取电子教学日志的相关数据
 *
 * created by qiuwei
 * version 1.0.0
 * 2016年04月06日
 */

import * as CONSTANTS from '../../constants/API';
import rp from '../requestProxy';
import { HTTP_RESULT } from '../../constants/protocol';
import { REPLY_DATA } from '../../constants/replyData';

const url = `${CONSTANTS.HOST}${CONSTANTS.ENUM_ON_SERVER}`;

/**
 * @description 获取电子教学日志
 * @public
 * @param  {string}  options.cityId   城市ID
 * @param  {string}  options.countyId 区县ID
 * @param  {string}  options.schoolId 学校ID
 * @param  {array}   options.subjects 科目数组
 * @param  {array}   options.grades   年级数组
 * @param  {integer} options.pageNum  当前页索引
 * @param  {integer} options.pageSize 页内容大小
 * @return {promise}                  教学日志集合
 */
export function journal({cityId, countyId, schoolId, subjects, grades, pageNum = 0, pageSize = 10}) {
	if (!cityId && !countyId && !schoolId) {
		throw new Error('查询电子教学日志缺少必要的参数');
	}

	let data = {
		target: 'teacher-teacher_id',
		filter: [],
		page_size: pageSize,
		page_num: pageNum
	};

	if (cityId) 
		data.filter.push({
			item: 'teacher-city_id',
			type: '=',
			value: cityId
		});

	if (countyId)
		data.filter.push({
			item: 'teacher-county_id',
			type: '=',
			value: countyId
		});

	if (schoolId)
		data.filter.push({
			item: 'teacher-school_id',
			type: '=',
			value: schoolId
		});

	if (subjects && subjects.length > 0)
		data.filter.push({
			item: 'teacher-subject',
			type: 'in',
			value: subjects.join(',')
		});

	if (grades && grades.length > 0) 
		data.filter.push({
			item: 'teacher-grade',
			type: 'in',
			value: grades.join(',')
		});

	return rp.post(url, data).then((result) => {
		if (result.code === HTTP_RESULT.SUCCESS) {
			let data = (result.data || []).map((item) => {
				return {
					'enum': item.enum,
					'info': JSON.parse(item.info)
				};
			});

			// 创建年级映射
			const GRADE_MAP = {
				'初一': '六年级',
				'初二': '七年级',
				'初三': '八年级',
				'初四': '九年级'
			};

			return Object.assign({}, REPLY_DATA, {
				code: HTTP_RESULT.SUCCESS,
				data: {
					list: data.map((item) => {
						if(GRADE_MAP[item.info.grade.text]) {
							item.info.grade.text = GRADE_MAP[item.info.grade.text];
						}
						return item;
					}),
					total_count: result.total_count,
					page_count: result.page_count
				}
			});
		}

		return result;
	});
}

